package com.wwf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wwf.mapper.IUserAuthCodeMapper;
import com.wwf.pojo.UserAuthCode;
import com.wwf.service.IAuthCodeService;
import com.wwf.util.RrandomCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author wwf
 * @date 2021年02月04日 15:12:27
 */
@Service
public class AuthCodeServiceImpl implements IAuthCodeService {
    @Autowired
    IUserAuthCodeMapper userAuthCodeMapper;
    
    @Override
    public String createCode(String email) {
        String code="";
        UserAuthCode userAuthCode = new UserAuthCode();
        userAuthCode.setEmail(email);
        QueryWrapper<UserAuthCode> userAuthCodeQueryWrapper = new QueryWrapper<>(userAuthCode);
        List<UserAuthCode> userAuthCodes = userAuthCodeMapper.selectList(userAuthCodeQueryWrapper);
        long currentTimes = System.currentTimeMillis();
        code = RrandomCode.getRanddomCode6();
        if(userAuthCodes != null && userAuthCodes.size() >0){
            UserAuthCode userAuthCode1 = userAuthCodes.get(0);
            Date expiretimeDate = userAuthCode1.getExpiretime();
            long expiretime = expiretimeDate.getTime();
            if(currentTimes>expiretime){//超时
                userAuthCode1.setCode(code);
                userAuthCode1.setCreatetime(new Date());
                long expireTimes = currentTimes+10*60*1000;
                userAuthCode1.setExpiretime(new Date(expireTimes));
                userAuthCodeMapper.updateById(userAuthCode1);
            }else{
                return userAuthCode1.getCode();
            }

        }else{
            userAuthCode.setCreatetime(new Date());
            long expireTimes = currentTimes+10*60*1000;
            userAuthCode.setExpiretime(new Date(expireTimes));
            userAuthCode.setCode(code);
            userAuthCodeMapper.insert(userAuthCode);
        }
        return code;
    }

    @Override
    public boolean checkCode(String email, String code) {
        List<UserAuthCode> userAuthCodes = userAuthCodeMapper.selectUserAuthCodeBy(email, code);
        if(userAuthCodes !=null && userAuthCodes.size()>0){
            return true;
        }
        return false;
    }
}
